package com.example.whereismystuff.views;

/**
 * AddItem Activity
 * Allows the User to register an Item to the Database
 * There a fields that must be filled before the
 * item can be added.
 */
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.example.whereismystuff.R;
import com.example.whereismystuff.classes.Item;
import com.example.whereismystuff.classes.ItemDataBaseAdapter;
import com.example.whereismystuff.classes.LoginDataBaseAdapter;
import com.example.whereismystuff.classes.User;
import com.example.whereismystuff.classes.UserDataManager;
import com.google.android.gms.maps.model.LatLng;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class AddItem extends Activity {

	private Button addItem, addImage, mapButton;
	private EditText e_itemName, e_itemDescription, e_zipCode;
	private RadioButton found, lost;
	private CheckBox tagElectronic, tagBook, tagPersonal;
	
	private boolean imageClicked;

	private final int MIN_STRING_LENGTH = 0;
	private final int TAGS_LENGTH = 3;
	private final int SELECT_ID = 0;

	private String itemName, itemDescription, foundString, zipCode;

	private AlertDialog.Builder alertDialog;
	private ArrayList<String> tags;
	private User user;
	private Intent i;

	private ImageView imageView;
	private Uri outputFileUri;

	private String username, image;
	private User curUser;

	private Bitmap bitmap;

	private final String DIALOG_MSG = "Please Input a Name";

	public static final String ITEM_TAG = "Item";
	
	LocationManager locMan;

	private ItemDataBaseAdapter itemDataBaseAdapter;

	/**
	 * Method used to Instantiate Object and set the Layout for the Activity
	 * 
	 * @param Bundle
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_item);

		itemDataBaseAdapter = new ItemDataBaseAdapter(this);
		itemDataBaseAdapter = itemDataBaseAdapter.open();
		
		

		imageView = (ImageView) findViewById(R.id.imageView);

		addImage = (Button) findViewById(R.id.addImageButton);
		addImage.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final File root = new File(Environment
						.getExternalStorageDirectory()
						+ File.separator
						+ "MyDir" + File.separator);
				root.mkdirs();
				final List<Intent> cameraIntents = new ArrayList<Intent>();
				final Intent captureIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				final PackageManager packageManager = getPackageManager();
				final List<ResolveInfo> listCam = packageManager
						.queryIntentActivities(captureIntent, 0);
				for (ResolveInfo res : listCam) {
					final String packageName = res.activityInfo.packageName;
					final Intent intent = new Intent(captureIntent);
					intent.setComponent(new ComponentName(
							res.activityInfo.packageName, res.activityInfo.name));
					intent.setPackage(packageName);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
					cameraIntents.add(intent);
				}

				// Filesystem.
				final Intent galleryIntent = new Intent();
				galleryIntent.setType("image/*");
				galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

				// Chooser of filesystem options.
				final Intent chooserIntent = Intent.createChooser(
						galleryIntent, "Select Source");

				// Add the camera options.
				chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
						cameraIntents.toArray(new Parcelable[] {}));

				startActivityForResult(chooserIntent, SELECT_ID);
			}
		});

		addItem = (Button) findViewById(R.id.addItemButton);
		mapButton = (Button) findViewById(R.id.a_goToMapButton);
		e_itemName = (EditText) findViewById(R.id.itemName);
		e_itemDescription = (EditText) findViewById(R.id.itemDescription);
		e_zipCode = (EditText) findViewById(R.id.zipCode);

		tagElectronic = (CheckBox) findViewById(R.id.isElectronic);
		tagBook = (CheckBox) findViewById(R.id.isBook);
		tagPersonal = (CheckBox) findViewById(R.id.isPersonal);

		found = (RadioButton) findViewById(R.id.found);
		lost = (RadioButton) findViewById(R.id.lost);

		alertDialog = new AlertDialog.Builder(this);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			username = extras.getString(Login.USERNAME_TAG);
			Toast.makeText(this, extras.getString(Login.USERNAME_TAG),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Code used to get other activities in the phone that contain Images so
	 * that they can be added to the Item.
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri selectedImageUri = null;
			if (requestCode == SELECT_ID) {
				final boolean isCamera;
				if (data == null) {
					isCamera = true;
				} else {
					final String action = data.getAction();
					if (action == null) {
						isCamera = false;
					} else {
						isCamera = action
								.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					}
				}

				if (isCamera) {
					selectedImageUri = outputFileUri;
				} else {
					selectedImageUri = data == null ? null : data.getData();
				}
			}
			try {
				imageView.setImageURI(selectedImageUri);
				outputFileUri = selectedImageUri;
				imageClicked = true;
			} catch (Exception e) {
			}
			;
		}
	}

	public String getPath(Uri uri) {
		Cursor cursor = getContentResolver().query(uri, null, null, null, null);
		cursor.moveToFirst();
		int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
		return cursor.getString(idx);
	}

	/**
	 * Method is called when the "Save" button is pressed. Saves all the
	 * information inputed into the database.
	 * 
	 * @param View
	 */
	public void onAddItem(View v) {
		Date now = new Date();
		itemName = e_itemName.getText().toString();
		itemDescription = e_itemDescription.getText().toString();
		tags = new ArrayList<String>();
		zipCode = e_zipCode.getText().toString();
		setUpTags();
		locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location lastLoc = locMan
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (lastLoc != null) {
			double lat = lastLoc.getLatitude();
			double lng = lastLoc.getLongitude();
		foundString = String.valueOf(found.isChecked());
		if (itemName.length() == MIN_STRING_LENGTH) {
			alertDialog.setMessage(DIALOG_MSG);
			alertDialog.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alertDialog.show();
		} else {
				if (imageClicked)
					itemDataBaseAdapter.insertEntry(
							username,
							itemName,
							itemDescription,
							DateFormat.getDateTimeInstance(DateFormat.SHORT,
									DateFormat.SHORT).format(now), foundString,
							tags, zipCode, getPath(outputFileUri), String.valueOf(lat), String.valueOf(lng));
				else
					itemDataBaseAdapter.insertEntry(
							username,
							itemName,
							itemDescription,
							DateFormat.getDateTimeInstance(DateFormat.SHORT,
									DateFormat.SHORT).format(now), foundString,
							tags, zipCode, String.valueOf(lat), String.valueOf(lng));
			}
			try {
				Class c = Class
						.forName("com.example.whereismystuff.views.ItemViewer");
				i = getIntent();
				Bundle extras = i.getExtras();
				i = new Intent(getApplicationContext(), c);
				i.putExtras(extras);
				startActivity(i);
				finish();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Method is called when the "Cancel" button is pressed returns you to the
	 * ItemView Activity.
	 * 
	 * @param v
	 */
	public void onCancel(View v) {
		try {
			Class c = Class
					.forName("com.example.whereismystuff.views.ItemViewer");
			i = getIntent();
			Bundle extras = i.getExtras();
			i = new Intent(getApplicationContext(), c);
			i.putExtras(extras);
			startActivity(i);
			finish();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Helper Method which add whether a tag is active or not.
	 */
	public void setUpTags() {
		tags.add("" + tagBook.isChecked());
		tags.add("" + tagElectronic.isChecked());
		tags.add("" + tagPersonal.isChecked());
	}
	/**
	 * Method is called when View Map Button is Pressed.
	 * 
	 * @param v
	 */
	public void goToMapView(View v) {
		if (e_itemName.getText().length() == 0) {
			alertDialog.setMessage("Please Fill Item Name Before Using Maps");
			alertDialog.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alertDialog.show();
		} else {
			try {
				Class c = Class
						.forName("com.example.whereismystuff.views.GoogleMapsView");
				i = new Intent(getApplicationContext(), c);
				Bundle extras = getIntent().getExtras();
				extras.putString("ItemName", e_itemName.getText().toString());
				i.putExtras(extras);
				startActivity(i);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
}
